package com.buddy.learn.javasource._thread.queue;

import java.util.LinkedList;

/**
 * @author Buddy
 * @date 2021/6/6
 */
public class MyQueue {

    private final LinkedList<Object> list = new LinkedList<>();
    private final Object obj = new Object();

    private void put(Object message){
        synchronized (obj){
            Integer mAX = 5;
            while (list.size() == mAX){
                try {
                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.add(message);
            obj.notify();
        }
    }

    public void get(){
        synchronized (obj){
            Integer mIN = 0;
            while (list.size() == mIN){
                try {
                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Object message = list.removeFirst();
            obj.notify();
        }
    }

    public static void main(String[] args) {
        final MyQueue t = new MyQueue();

        new Thread(new Runnable() {
            @Override
            public void run() {
                t.put("a");
                t.put("b");
                t.put("c");
                t.put("d");
            }
        },"t1").start();



        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    t.get();
                    Thread.sleep(1000);
                    t.get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"t2").start();
    }
}
